import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RoleHierarchy, UserRole } from './entities/user.entity';
import { ROLES_KEY } from 'src/decorator/roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRole = this.reflector.get<UserRole>(ROLES_KEY, context.getHandler());
    if (!requiredRole) {
      return true; // 如果没有设置角色，默认允许访问
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user || !this.hasAccess(user.role, requiredRole)) {
      throw new ForbiddenException('你没有权限访问此资源');
    }

    return true;
  }

  private hasAccess(userRole: UserRole, requiredRole: UserRole): boolean {
    // 比较角色层级
    return RoleHierarchy[userRole] >= RoleHierarchy[requiredRole];
  }
}
